package com.example.select_lesson;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.balysv.materialmenu.MaterialMenuDrawable;

import java.util.ArrayList;
import java.util.List;


public class SelectLessonTestActivity extends ActionBarActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

    public static void actionStart(Context context, String studentId, ArrayList<String> classList) {
        Intent intent = new Intent(context, SelectLessonTestActivity.class);
        intent.putExtra("student_id", studentId);
        intent.putStringArrayListExtra("class_list", classList);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }

    private MaterialMenuDrawable materialMenu;
    private int itemsNumber = 0;
    public static int[] selectClassId;
    private TextView next;
    private SelectedClassInformationTestAdapter adapter;
    private BounceListView mListView;
    private ArrayList<String> classList;
    private String studentId;
    private SQLiteDatabase db;
    private MyDataBaseHelper dbHelper;
    /**
     * 存放课程名字的list
     */
    private ArrayList<String> lessonNameList = new ArrayList<String>();
    /**
     * 存放课程Id的list
     */
    private ArrayList<Integer> classIdList = new ArrayList<Integer>();
    /**
     * 存放课程已选选择人数的list
     */
    private ArrayList<Integer> selectedStudentNumberList = new ArrayList<Integer>();
    /**
     * 存放课程最多选择人数的list
     */
    private ArrayList<Integer> studentNumberList = new ArrayList<Integer>();
    /**
     * 存放课程时间的list
     */
    private ArrayList<String> lessonTimeList = new ArrayList<String>();
    /**
     * 存放教师Id的list
     */
    private ArrayList<Integer> teacherIdList = new ArrayList<Integer>();
    /**
     * 存放教师名字的list
     */
    private ArrayList<String> teacherNameList = new ArrayList<String>();

    /**
     * 存放所有要显示在listView上的信息的list
     */
    private ArrayList<SelectedClassInformationTest> selectedClassInformationTestList = new ArrayList<SelectedClassInformationTest>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_lesson_test);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.my_dark_blue));
        }
        classList = getIntent().getStringArrayListExtra("class_list");
        studentId = getIntent().getStringExtra("student_id");

        // 数据库
        dbHelper = new MyDataBaseHelper(this, "StudentManager.db", null, 1);
        dbHelper.getWritableDatabase();
        db = dbHelper.getWritableDatabase();

        for (int i = 0; i < classList.size(); ++i) {
            Cursor cursor = db.rawQuery("select * from LESSON where lessonName=?",
                    new String[] {classList.get(i) + ""});
            if (cursor.moveToFirst()) {
                do {
                    lessonNameList.add(cursor.getString(cursor.getColumnIndex("lessonName")));
                    classIdList.add(cursor.getInt(cursor.getColumnIndex("lessonId")));
                    studentNumberList.add(cursor.getInt(cursor.getColumnIndex("studentNumber")));
                    lessonTimeList.add(cursor.getString(cursor.getColumnIndex("lessonTime")));
                    teacherIdList.add(cursor.getInt(cursor.getColumnIndex("teacherId")));
                    itemsNumber++;
                } while (cursor.moveToNext());
            }
            cursor.close();
        }

        selectClassId = new int[itemsNumber];
        for (int i = 0; i < itemsNumber; ++i) {
            selectClassId[i] = -1;
        }

        for (int i = 0; i < classIdList.size(); ++i) {
            Cursor cursor = db.rawQuery("select * from SELECT_LESSON where classId=?",
                    new String[] {classIdList.get(i) + ""});
            int studentNumber = 0;
            if (cursor.moveToFirst()) {
                do {
                    studentNumber++;
                } while (cursor.moveToNext());
            }
            selectedStudentNumberList.add(studentNumber);
            cursor.close();
        }
        for (int i = 0; i < teacherIdList.size(); ++i) {
            Log.d("teacherName", teacherIdList.get(i) + "");
            Cursor cursor = db.rawQuery("select * from TEACHER where teacherId=?",
                    new String[] {teacherIdList.get(i) + ""});
            if (cursor.moveToFirst()) {
                do {
                    Log.d("teacherName", "aaa");
                    teacherNameList.add(cursor.getString(cursor.getColumnIndex("teacherName")));
                } while (cursor.moveToNext());
            }
            cursor.close();
        }

        for (int i = 0; i < lessonNameList.size(); ++i) {
            SelectedClassInformationTest selectedClassInformationTest =
                    new SelectedClassInformationTest(lessonNameList.get(i),
                            studentNumberList.get(i),
                            selectedStudentNumberList.get(i),
                            lessonTimeList.get(i),
                            teacherNameList.get(i)
                    );
            selectedClassInformationTestList.add(selectedClassInformationTest);
        }


        setToolbar();

        mListView = (BounceListView) findViewById(R.id.list_view);
        adapter = new SelectedClassInformationTestAdapter(SelectLessonTestActivity.this, R.layout.item_search_class, selectedClassInformationTestList);
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(this);
        next = (TextView) findViewById(R.id.tv_next);
        next.setOnClickListener(this);
    }

    private void setToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("  选课测试");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                switch (materialMenu.getIconState()) {
                    case BURGER:
                        break;
                    case ARROW:
                        materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW, false);
                        finish();
                        break;
                    case X:
                        break;
                    case CHECK:
                        break;
                }

            }
        });
        materialMenu = new MaterialMenuDrawable(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN);
        materialMenu.animateIconState(MaterialMenuDrawable.IconState.ARROW, false);
        toolbar.setNavigationIcon(materialMenu);
        materialMenu.setNeverDrawTouch(true);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_select_lesson_test, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (selectClassId[position] == -1) {
            selectClassId[position] = classIdList.get(position);
        } else {
            selectClassId[position] = -1;
        }
        adapter.notifyDataSetChanged();
        Boolean isNull = true;
        for (int i = 0; i < itemsNumber; ++i) {
            if (selectClassId[i] != -1) {
                isNull = false;
            }
        }
        if (!isNull) {
            next.setVisibility(View.VISIBLE);
        } else {
            next.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_next:
                dbHelper = new MyDataBaseHelper(this, "StudentManager.db", null, 1);
                db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                for (int i = 0; i < itemsNumber; ++i) {
                    if (selectClassId[i] != -1) {
                        values = new ContentValues();
                        values.put("studentId", studentId);
                        values.put("classId", selectClassId[i]);
                        db.insert("SELECT_LESSON", null, values);
                        values.clear();
                    }
                }
                db.close();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提交成功");
                builder.setMessage("返回主页面");
                builder.setNegativeButton("好的", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        HomeActivity.actionStart(getApplicationContext(), studentId);
                        dialog.cancel();
                    }
                });
                builder.show();
            break;
        }
    }
}
/**
 * 新建一个已选课程信息类
 * 便于之后给listView传递数据
 */
class SelectedClassInformationTest {
    private String lessonName;
    private int studentNumber;
    private int selectedStudentNumber;
    private String lessonTime;
    private String teacherName;


    SelectedClassInformationTest(String lessonName, int studentNumber, int selectedStudentNumber,
                             String lessonTime, String teacherName) {
        this.lessonName = lessonName;
        this.studentNumber = studentNumber;
        this.selectedStudentNumber = selectedStudentNumber;
        this.lessonTime = lessonTime;
        this.teacherName = teacherName;
    }
    public String getLessonName() {
        return lessonName;
    }

    public void setLessonName(String lessonName) {
        this.lessonName = lessonName;
    }

    public int getStudentNumber() {
        return studentNumber;
    }

    public void setStudentNumber(int studentNumber) {
        this.studentNumber = studentNumber;
    }

    public int getSelectedStudentNumber() {
        return selectedStudentNumber;
    }

    public void setSelectedStudentNumber(int selectedStudentNumber) {
        this.selectedStudentNumber = selectedStudentNumber;
    }

    public String getLessonTime() {
        return lessonTime;
    }

    public void setLessonTime(String lessonTime) {
        this.lessonTime = lessonTime;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }
}

class SelectedClassInformationTestAdapter extends ArrayAdapter<SelectedClassInformationTest> {

    private int resouceId;


    public SelectedClassInformationTestAdapter(Context context, int resource, List<SelectedClassInformationTest> objects) {
        super(context, resource, objects);
        resouceId = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        SelectedClassInformationTest selectedClassInformationTest = getItem(position);
        View view;
        view = LayoutInflater.from(getContext()).inflate(resouceId, null);
        TextView textView = (TextView) view.findViewById(R.id.tv_item);
        textView.setText("课程名：" + selectedClassInformationTest.getLessonName()
                + "\n课程时间：" + selectedClassInformationTest.getLessonTime()
                + "\n已选人数/总人数：" + selectedClassInformationTest.getSelectedStudentNumber()
                + "/" + selectedClassInformationTest.getStudentNumber()
                + "\n教师：" + selectedClassInformationTest.getTeacherName());
        if (SelectLessonTestActivity.selectClassId[position] != -1) {
            view.setBackgroundColor(view.getResources().getColor(R.color.my_light_light_blue));
        }
        return view;
    }

}